#pragma once

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include <sys/wait.h>
#include <functional>
#include <pthread.h>

#include "nocopy.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
#include "ThreadPool.hpp"

static const uint16_t gport = 8888;
static const int blcklog = 8;
static const int gsockfd = -1;

using namespace log_ns;
using task_t = std::function<void()>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class TcpServer : public nocopy
{
public:
    TcpServer(const uint16_t port = gport)
        : _port(port),
          _listensockfd(gsockfd),
          _isrunning(0)
    {
    }

    void InitServer()
    {
        _listensockfd = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensockfd < 0)
        {
            LOG(FATAL, "Bind error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "Socket success!\n");
        struct sockaddr_in addr;
        addr.sin_port = htons(_port);
        addr.sin_addr.s_addr = INADDR_ANY;
        addr.sin_family = AF_INET;

        if (::bind(_listensockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        {
            LOG(FATAL, "Bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "Bind success!\n");

        if (::listen(_listensockfd, blcklog) < 0)
        {
            LOG(FATAL, "listen error!\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success!\n");
    }

    class ThreadData
    {
    public:
        int _sockfd;
        InetAddr _addr;
        TcpServer *_self;

        ThreadData(int sockfd, InetAddr addr, TcpServer *self)
            : _sockfd(sockfd), _addr(addr), _self(self)
        {
        }
    };

    void Loop()
    {
        _isrunning = 1;
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

            int sockfd = accept(_listensockfd, (struct sockaddr *)&client, &len);
            InetAddr addr(client);

            // version - 0
            // Server(sockfd, addr);

            // version - 1
            // int id = fork();
            // if (id == 0)
            // {
            //     ::close(_listensockfd);
            //     if (fork() > 0)
            //         exit(0);

            //     Server(sockfd, addr);

            //     exit(0);
            // }
            // ::close(sockfd);
            // int n = waitpid(id, nullptr, 0);
            // if (n > 0)
            // {
            //     LOG(DEBUG, "waitpid seccuss\n");
            // }

            // version - 2
            // pthread_t thread;
            // ThreadData* td = new ThreadData(sockfd, addr, this);
            // pthread_create(&thread, nullptr, Execute, td);

            // version - 3
            task_t t = std::bind(&TcpServer::Server, this, sockfd, addr);
            ThreadPool<task_t>::GetInstance()->Equeue(t);
        }
        _isrunning = 0;
    }

    static void *Execute(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData* td = static_cast<ThreadData*>(args);
        td->_self->Server(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }

    void Server(int sockfd, InetAddr &addr)
    {
        while (1)
        {
            char buffer[1024];
            int n = read(sockfd, buffer, sizeof(buffer) - 1);
            if (n > 0)
            {
                buffer[n] = 0;
                std::string echo_string = "[server echo]";
                echo_string += buffer;
                write(sockfd, echo_string.c_str(), echo_string.size());
                LOG(INFO, "echo success\n");
            }
            else if (n == 0)
            {
                LOG(INFO, "client %s quit\n", addr.AddrStr().c_str());
                break;
            }
            else
            {
                LOG(ERROR, "read error\n");
                break;
            }
        }
        ::close(sockfd);
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    int _listensockfd;
    bool _isrunning;
};
